<?php
namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;

use App\Models\User;
use App\Models\UserSafe;

use App\Services\CouponService;
use App\Services\SMSService;
use App\Services\UserService;
use Qiniu\Storage\BucketManager;

/**
 *
 * 用户控制器
 *
 * @author maqu
 *
 */
class UserController extends BaseController {

    //用户帐号登录
    /**
     * @return mixed
     */
    public function login(){
      
        $username = Input::get('user_name');
        $password = Input::get('password');

        if (!$username)
            return $this->failure('请填写用户名');
            
        if (!$password)
            return $this->failure('请填写密码');

        $credentials = array('user_name' => $username, 'password' => $password);


        $luser = User::where('user_name',$username)
            ->where('password',$password)
            ->first();

        if ($luser) {
            
            // Get current user
            $current_user = $luser;
                
            // Retrieve current user info
            $info = array();
    
            // Data fields to return
            // birthday just below refer to baby's birthday
            $fields = array('user_id', 'user_name','phone_mob', 'portrait','nickname', 'wx_nickname','wx_openid',
                'ugrade', 'birthday','domicile','intro');
            // Loop through fields and set key/value of the info array
            foreach ($fields as $field) {
                $info[$field] = $current_user->$field;                      
            }
            $info['portrait']=complete_url($info['portrait'].'?t='.gmtime());

            $access_token = uuid();
            $info['access_token'] =$access_token;
            $logintime = gmtime();

            //insert into user_safe
            $count = DB::table('user_safe')->where('user_id',$current_user['user_id'])->count();
            if($count){
                DB::table('user_safe')->where('user_id',$current_user['user_id'])
                    ->update(
                    array(
                        'login_time'=>$logintime,
                        'login_pwd'=>$password,
                        'expire_time'=>$logintime+7*24*60*60,
                        'access_token'=>$access_token,
                    ));

            } else {
                DB::table('user_safe')->insert(
                    array(
                        'user_id'=>$current_user['user_id'],
                        'login_time'=>$logintime,
                        'login_pwd'=>$password,
                        'expire_time'=>$logintime+7*24*60*60,
                        'access_token'=>$access_token,
                    )
                );
            }

            event('user.login',$current_user);

            return $this->success($info);
        } else {        
            return $this->failure('用户名或密码不正确');
        }
    }

//    //用户短信登录
//    /**
//     * @return mixed
//     */
//    public function smslogin(SMSService $smsService,UserService $userService){
//
//        // validate
//        $input = Input::all();
//
//        $rules = array(
//            'phone'  => 'required|phone',
//            'code'  => 'required'
//        );
//
//        $validation = Validator::make($input, $rules);
//        if ($validation->fails()){
//            return $this->failure($validation->messages());
//        }
//
//        $phone = Input::get('phone');
//        $code = Input::get('code');
//
//        $result =$smsService->checkCode($phone,1,$code);
//        if(!$result['result']){
//            return $this->failure($result['msg']);
//        }
//
//        $result =$userService->loginBySMS($phone,$code);
//        if(!$result['result']){
//            return $this->failure($result['msg']);
//        }
//
//        return $this->success($result['data']);
//
//    }

    //绑定手机
    public function bind_mobile($user_id,SMSService $smsService,UserService $userService){

        // validate
        $input = Input::all();

        $rules = array(
            'phone'  => 'required|phone',
            'code'  => 'required'
        );

        $validation = Validator::make($input, $rules);
        if ($validation->fails()){
            return $this->failure($validation->messages());
        }

        $phone = Input::get('phone');
        $code = Input::get('code');

        $result =$smsService->checkCode($phone,SMS_CODE_TYPE_BIND_MOBILE,$code);
        if(!$result['result']){
            return $this->failure($result['msg']);
        }

        $result =$userService->bind_mobile($user_id,$phone);
        if(!$result['result']){
            return $this->failure($result['msg']);
        }

        return $this->success($result['data']);

    }

    //创建用户（第三方一件键登录时用）
    public function createIfnotExistQQ(){

        // validate
        $openid = Input::get('openid');
        $access_token = Input::get('third_accesstoken');
        if(!$openid || !$access_token){
            return $this->args_invalid();
        }
Log::debug('openid:'.$openid.' token:'.$access_token);

        //api
        require_once base_path() . '/vendor/qq/PHP_SDK_V3.0.9/lib/SnsNetwork.php';

        $url=config('maqu.QQ_API_URL') . '/user/get_user_info';
        $params = array(
            'openid' => $openid,
            'access_token' => $access_token,
            'oauth_consumer_key' => config('maqu.QQ_APP_ID'),
        );
        $ret = \SnsNetwork::makeRequest($url, $params, '', 'get', 'https');

        //$result
        if($ret['result']===false){
            return $this->failure("QQ登录时失败、请联系管理员。");
        }

        $result = json_decode($ret['msg'],true);

        if($result['ret']!=0){
            Log::debug('QQ登录时失败 ret:'.$result['ret'].'  msg:'.$result['msg']);
            return $this->failure("QQ登录时失败");
        }

        $user = User::where('qq_openid',$openid)->where('user_state',0)->first();
        if(!$user){
            $user = User::where('qq_openid',$openid)->first();
        }

        //nickname	昵称。gender	性别。figureurl	头像URL。
        if(!$user){

            DB::table('member')->insert(
                array('user_name'=>$openid,
                    'gender'=>$result['gender']=='男'?1:$result['gender']=='女'?2:0,
                    'portrait'=>$result['figureurl_qq_2'],
                    'qq_openid'=>$openid,
                    'nickname'=>$result['nickname'],
                    'qq_nickname'=>$result['nickname'],
                    'reg_time'=>gmtime(),
                    'password'=>md5($openid.config('app.key'))));

            $user = User::where('qq_openid',$openid)->first();

        }

        if (!$user) {
            return $this->failure('用户名或密码不正确');
        }

        //更新最新用户信息
        $portrait =$this->fetchAsPortrait($result['figureurl_qq_2'],$user->user_id);
        DB::table('member')->where('user_id',$user->user_id)
            ->update([
            'portrait'=>$portrait,
            'gender'=>$result['gender']=='男'?1:$result['gender']=='女'?2:0,
            'nickname'=>$result['nickname'],
            'qq_nickname'=>$result['nickname'],
            'user_state'=>0
        ]);

        // Get current user
        $current_user =$user;

        // Retrieve current user info
        $info = array();

        // Data fields to return
        // birthday just below refer to baby's birthday
        $fields = array('user_id', 'user_name', 'phone_mob','portrait','nickname','wx_nickname');

        // Loop through fields and set key/value of the info array
        foreach ($fields as $field) {
            $info[$field] = $current_user->$field;
        }

        $time =gmtime();

        $access_token = uuid();
        $info['access_token'] =$access_token;

        //insert into user_safe
        $userSafe = UserSafe::find($current_user->user_id);
        if($userSafe){

            $userSafe->login_time=$time;
            $userSafe->login_pwd= $current_user->password;
            $userSafe->expire_time=$time+7*24*60*60;
            $userSafe->access_token=$access_token;
            $userSafe->save();
        } else {

            $userSafe = new UserSafe();

            $userSafe->user_id=$current_user->user_id;
            $userSafe->login_time=$time;
            $userSafe->login_pwd= $current_user->password;
            $userSafe->expire_time=$time+7*24*60*60;
            $userSafe->access_token=$access_token;
            $userSafe->save();
        }

        event('user.login',$current_user);

        return $this->success($info);
    }

    //创建用户（第三方一件键登录时用）
    public function createIfnotExistWX(){
        // validate

        $openid = Input::get('openid');
        $access_token = Input::get('third_accesstoken');
        if(!$openid || !$access_token){
            return $this->args_invalid();
        }
        Log::debug('openid:'.$openid.' token:'.$access_token);

        //api
        require_once base_path() . '/vendor/qq/PHP_SDK_V3.0.9/lib/SnsNetwork.php';

        $url=config('maqu.WX_API_URL') . '/sns/userinfo';
        $params = array(
            'openid' => $openid,
            'access_token' => $access_token
        );
        $ret = \SnsNetwork::makeRequest($url, $params, '', 'get', 'https');

        //$result
        if($ret['result']===false){
            return $this->failure("微信登录时失败、请联系管理员。");
        }

        $result = json_decode($ret['msg'],true);

        if(!array_key_exists('unionid',$result)){
            return $this->failure('unionid获取失败');
        }

        $wx_unionid = $result['unionid'];

        $user = User::where('wx_unionid',$wx_unionid)->where('user_state',0)->first();
        if(!$user){
            $user = User::where('wx_unionid',$wx_unionid)->first();
        }
        $real_name =array_key_exists('nickname',$result)?$result['nickname']:'';
        $gender =array_key_exists('sex',$result)?($result['sex']=='1'?1:$result['sex']=='2'?2:0):0;
        $portrait =array_key_exists('headimgurl',$result)?$result['headimgurl']:'';
        //nickname	昵称。gender	性别。figureurl	头像URL。
        if(!$user){
            DB::table('member')->insert(
                array('user_name'=>$openid,
                    'gender'=>$gender,
                    'portrait'=>$portrait,
                    'password'=>md5($openid.config('app.key')),
                    'wx_openid'=>$openid,
                    'wx_unionid'=>$wx_unionid,
                    'nickname'=>$real_name,
                    'wx_nickname'=>$real_name,
                    'reg_time'=>gmtime(),
                    'feed_config'=>''));

            $user = User::where('wx_unionid',$wx_unionid)->first();
        }

        if (!$user) {
            return $this->failure('用户名或密码不正确');
        }

        //更新最新用户信息
        $portrait =$this->fetchAsPortrait($portrait,$user->user_id);
        DB::table('member')
            ->where('user_id',$user->user_id)
            ->update([
                'wx_openid'=>$openid,
            'portrait'=>$portrait,
            'gender'=>$gender,
            'nickname'=>$real_name,
            'wx_nickname'=>$real_name,
            'user_state'=>0
        ]);

        // Get current user
        $current_user = $user;

        // Retrieve current user info
        $info = array();

        // Data fields to return
        // birthday just below refer to baby's birthday
        $fields = array('user_id', 'user_name', 'phone_mob','portrait','nickname','wx_nickname');

        // Loop through fields and set key/value of the info array
        foreach ($fields as $field) {
            $info[$field] = $current_user->$field;
        }

        $time =gmtime();

        $access_token = uuid();
        $info['access_token'] =$access_token;
        $logintime = $time;

        //insert into user_safe
        $userSafe = UserSafe::find($current_user->user_id);
        if($userSafe){

            $userSafe->login_time=$time;
            $userSafe->login_pwd= $current_user->password;
            $userSafe->expire_time=$time+7*24*60*60;
            $userSafe->access_token=$access_token;
            $userSafe->save();
        } else {

            $userSafe = new UserSafe();

            $userSafe->user_id=$current_user->user_id;
            $userSafe->login_time=$time;
            $userSafe->login_pwd= $current_user->password;
            $userSafe->expire_time=$time+7*24*60*60;
            $userSafe->access_token=$access_token;
            $userSafe->save();
        }

        event('user.login',$current_user);

        return $this->success($info);
    }

    //微信内授权登陆
    public function createIfnotExistWXCode(){

        // validate
        $appid = config('maqu.WXPB_APP_ID');
        $secret = config('maqu.WXPB_APP_KEY');
        $code = "";

        if(Input::has('code'))
            $code = Input::get('code');
        else
            return $this->failure("请从微信进入");

        Log::debug("createIfnotExistWXCode appid:$appid secret:$secret code:$code");

        $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';

        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$get_token_url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
        if(curl_errno($ch)){//出错则显示错误信息
            return $this->failure(curl_error($ch));
        }
        curl_close($ch);

        $json_obj = json_decode($res,true);

        if(!isset($json_obj['access_token'])){
            return $this->failure($json_obj['errmsg']);
        }

        $openid = $json_obj['openid'];

        $access_token = $this->getAccessToken($appid,$secret);

        $get_user_info_url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';

        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$get_user_info_url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
        if(curl_errno($ch)){//出错则显示错误信息
            return $this->failure(curl_error($ch));
        }
        curl_close($ch);

        //解析json
        $result=$this->userTextEncode($res);
        $result = json_decode($result,true);
        if(!isset($result['openid'])){
            return $this->failure($result['errmsg']);
        }

//        if(!array_key_exists('unionid',$result)){
//            return $this->failure('unionid获取失败');
//        }
//
//        $wx_unionid = $result['unionid'];
//        $user = User::where('wx_unionid',$wx_unionid)->where('user_state',0)->first();
//        if(!$user){
//            $user = User::where('wx_unionid',$wx_unionid)->first();
//        }
        $real_name =array_key_exists('nickname',$result)?$result['nickname']:'';
        $gender =array_key_exists('sex',$result)?($result['sex']=='1'?1:$result['sex']=='2'?2:0):0;
        $portrait =array_key_exists('headimgurl',$result)?$result['headimgurl']:'';

       // Log::debug("createIfnotExistWXCode unionid:$wx_unionid openid:$openid nickname:$real_name");

        //nickname	昵称。gender	性别。figureurl	头像URL。
        $user = User::where('wx_openid',$openid)->where('user_state',0)->first();
        if(!$user){
            DB::table('member')->insert(
                array('user_name'=>$openid,
                    'gender'=>$gender,
                    'portrait'=>$portrait,
                    'password'=>md5($openid.config('app.key')),
                    'wx_openid'=>$openid,
                    //'wx_unionid'=>$wx_unionid,
                    'nickname'=>$real_name,
                    'wx_nickname'=>$real_name,
                    'user_type'=>3,
                    'reg_time'=>gmtime(),
                    'phone_mob'=>'',
                    'domicile'=>'',
                    'intro'=>'',
                    'feed_config'=>''));

            $user = User::where('wx_openid',$openid)->first();
        }

        if (!$user) {
            return $this->failure('用户名或密码不正确');
        }

        //更新最新用户信息
        $portrait =$this->fetchAsPortrait($portrait,$user->user_id);
        DB::table('member')
            ->where('user_id',$user->user_id)
            ->update([
                'wx_openid'=>$openid,
                'portrait'=>$portrait,
                'gender'=>$gender,
                'nickname'=>$real_name,
                'wb_nickname'=>$real_name,
                'user_state'=>0
            ]);

        // Get current user
        $current_user = $user;

        // Retrieve current user info
        $info = array();

        // Data fields to return
        // birthday just below refer to baby's birthday
        $fields = array('user_id', 'user_name', 'phone_mob','portrait','nickname','wx_nickname','domicile','intro','wx_openid',
        'ugrade', 'birthday');

        // Loop through fields and set key/value of the info array
        foreach ($fields as $field) {
            $info[$field] = $current_user->$field;
        }

        $time =gmtime();

        $access_token = uuid();
        $info['access_token'] =$access_token;
        $logintime = $time;

        //insert into user_safe
        $userSafe = UserSafe::find($current_user->user_id);
        if($userSafe){

            $userSafe->login_time=$time;
            $userSafe->login_pwd= $current_user->password;
            $userSafe->expire_time=$time+7*24*60*60;
            $userSafe->access_token=$access_token;
            $userSafe->save();
        } else {

            $userSafe = new UserSafe();

            $userSafe->user_id=$current_user->user_id;
            $userSafe->login_time=$time;
            $userSafe->login_pwd= $current_user->password;
            $userSafe->expire_time=$time+7*24*60*60;
            $userSafe->access_token=$access_token;
            $userSafe->save();
        }

        event('user.login',$current_user);

        return $this->success($info);

    }

    /**
    把用户输入的文本转义（主要针对特殊符号和emoji表情）
     */
    function userTextEncode($str){
        if(!is_string($str))return $str;
        if(!$str || $str=='undefined')return '';

        $text = json_encode($str); //暴露出unicode
        $text = preg_replace_callback('/(\\\u[ed][0-9a-f]{3})/i',function($str){
            return addslashes($str[0]);
        },$text); //将emoji的unicode留下，其他不动，这里的正则比原答案增加了d，因为我发现我很多emoji实际上是\ud开头的，反而暂时没发现有\ue开头。
        return json_decode($text);
    }
    /**
    解码上面的转义
     */
    function userTextDecode($str){
        $text = json_encode($str); //暴露出unicode
        $text = preg_replace_callback('/\\\\\\\\/i',function($str){
            return '\\';
        },$text); //将两条斜杠变成一条，其他不动
        return json_decode($text);
    }

    private function getAccessToken($appid,$secret) {
        // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
        $data = json_decode(file_get_contents(__DIR__ ."/../access_token.json"));

        if ($data->expire_time < time()||!$this->wxCheckAccessToken()) {
            // 如果是企业号用以下URL获取access_token
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
            $res = json_decode($this->httpGet($url));

            $access_token = $res->access_token;
            if ($access_token) {
                $data->expire_time = time() + 7000;
                $data->access_token = $access_token;
                $fp = fopen(__DIR__ ."/../access_token.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        } else {
            $access_token = $data->access_token;
        }
        return $access_token;
    }

    private function  wxCheckAccessToken(){

        $appid = config('maqu.WXPB_APP_ID');
        $secret = config('maqu.WXPB_APP_KEY');

        $data = json_decode(file_get_contents(__DIR__ ."/../access_token.json"));

        $url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=".$data->access_token;
        $res = json_decode($this->httpGet($url));
        if(!isset($res->ip_list)){
            return false;
        }
        return true;
    }

    private function httpGet($url) {

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }

    //创建用户（第三方一件键登录时用）openid=uid
    public function createIfnotExistWB(){

        // validate
        $openid = Input::get('openid');
        $access_token = Input::get('third_accesstoken');
        if(!$openid || !$access_token){
            return $this->args_invalid();
        }
        Log::debug('openid:'.$openid.' token:'.$access_token);

        //api
        require_once base_path() . '/vendor/qq/PHP_SDK_V3.0.9/lib/SnsNetwork.php';

        $url=config('maqu.WB_API_URL') . '/2/users/show.json';
        $params = array(
            'source'=>config('maqu.WB_APP_KEY'),
    		'uid' => $openid,
    		'access_token' => $access_token
    	);
    	$ret = \SnsNetwork::makeRequest($url, $params, '', 'get', 'https');

    	//$result
    	if($ret['result']===false){
    	    return $this->failure("微博登录时失败、请联系管理员。");
    	}

        $result = json_decode($ret['msg'],true);

        $user = User::where('wb_openid',$openid)->where('user_state',0)->first();
        if(!$user){
            $user = User::where('wb_openid',$openid)->first();
        }
        $real_name =array_key_exists('screen_name',$result)?$result['screen_name']:'';
        $gender =array_key_exists('gender',$result)?($result['gender']=='m'?1:$result['gender']=='f'?2:0):0;
        $portrait =array_key_exists('profile_image_url',$result)?$result['profile_image_url']:'';

        //nickname	昵称。gender	性别。figureurl	头像URL。
        if(!$user){
            DB::table('member')->insert(
                array('user_name'=>$openid,
                    'gender'=>$gender,
                    'portrait'=>$portrait,
                    'password'=>md5($openid.config('app.key')),
                    'wb_openid'=>$openid,
                    'nickname'=>$real_name,
                    'wb_nickname'=>$real_name,
                    'reg_time'=>gmtime(),
                    'feed_config'=>''));

            $user = User::where('wb_openid',$openid)->first();
        }

        $user = User::where('wb_openid',$openid)->first();

        if (!$user) {
            return $this->failure('用户名或密码不正确');
        }

        //更新最新用户信息
        $portrait =$this->fetchAsPortrait($portrait,$user->user_id);
        DB::table('member')->where('user_id',$user->user_id)
            ->update([
            'portrait'=>$portrait,
            'gender'=>$gender,
            'nickname'=>$real_name,
            'wb_nickname'=>$real_name,
            'user_state'=>0
        ]);

        // Get current user
        $current_user =$user;

        // Retrieve current user info
        $info = array();

        // Data fields to return
        // birthday just below refer to baby's birthday
        $fields = array('user_id', 'user_name', 'phone_mob','portrait','nickname','wx_nickname');

        // Loop through fields and set key/value of the info array
        foreach ($fields as $field) {
            $info[$field] = $current_user->$field;
        }

        $time =gmtime();

        $access_token = uuid();
        $info['access_token'] =$access_token;
        $logintime = $time;

        //insert into user_safe
        $userSafe = UserSafe::find($current_user->user_id);
        if($userSafe){

            $userSafe->login_time=$time;
            $userSafe->login_pwd= $current_user->password;
            $userSafe->expire_time=$time+7*24*60*60;
            $userSafe->access_token=$access_token;
            $userSafe->save();
        } else {

            $userSafe = new UserSafe();

            $userSafe->user_id=$current_user->user_id;
            $userSafe->login_time=$time;
            $userSafe->login_pwd= $current_user->password;
            $userSafe->expire_time=$time+7*24*60*60;
            $userSafe->access_token=$access_token;
            $userSafe->save();
        }

        event('user.login',$current_user);

        return $this->success($info);
    }

    //用户注销
    /**
     * @param $user_id
     * @return mixed
     */
    public function logout($user_id){
    
        if(!$user_id){
            return $this->args_invalid();
        }

        $user=User::findOrFail($user_id);
        if(!$user){
            return $this->failure('用户不存在');
        }

        event('user.logout',$user);

        return $this->success(null);
    }

    //用户注册
    /**
     * @return mixed
     */
    public function register(){

        // validate
        $input = Input::all(); 
        
        $rules = array(
            'user_name'  => 'required|unique:member|phone',
            'password'  => 'required|confirmed|min:6|max:16',
            'password_confirmation'  => 'required|same:password',
            'code'  => 'required'
        );
               
        $validation = Validator::make($input, $rules);
        if ($validation->fails()){
            return $this->failure($validation->messages());
        }

        //用户名
        $user_name = Input::get('user_name');
        //密码
        $password = Input::get('password');
        //验证码
        $code = Input::get('code');

        if(!$this->check_username($user_name)){
			 return $this->failure('该用户名已被注册');
        }

		$log = DB::table('checkcode')->where('mobile',$user_name)
			->where('codetype',SMS_CODE_TYPE_REGISTER)
			->where('status',0)
			->where('code',$code)->orderBy('create_time','desc')->first();

		if(!$log)
			return $this->failure('输入的验证码不匹配.');
       
		if($log->status != 0)
			return $this->failure('验证码已使用，请重新获取.');

		if($log->expire_time < gmtime())
			return $this->failure('验证码已过期，请重新获取.');
       
		if($log->code != $code)
			return $this->failure('输入的验证码不匹配.');
       
        DB::table('checkcode')->where('id',$log->id)->update(
			array('status'=>1));

        $user = array(
            'user_type' => USER_TYPE_CONSUMER,
            'nickname'=>$user_name,
            'user_name' => $user_name,
            'phone_mob' => $user_name,
            'password' => md5($password),
            'domicile'=>'',
            'intro'=>'这家伙很懒，什么都没留下',
            'reg_time' =>gmtime());

        $user_id=DB::table('member')->insertGetId($user);

        //$user['user_id'] =$user_id;
        $user =User::findOrFail($user_id);

        event('user.register',$user);

        return $this->success(null);
    }

    //密码找回
    /**
     * @param $user_id
     * @return mixed
     */
    public function findPwd(){
    
        // validate
        $input = Input::all();

        $rules = array(
            'user_name'=>'required',
            'password'  => 'required|confirmed|min:6|max:16',
            'code'  => 'required'
        );
        
        $validation = Validator::make($input, $rules);
        if ($validation->fails()){
            return $this->failure($validation->messages());
        }

        $password = Input::get('password');
        $code = Input::get('code');
        $user_name = Input::get('user_name');

        $user=DB::table('member')
            ->where('user_name',$user_name)->first();
        if(!$user){
            return $this->failure('user not exist!');
        }

        $mobile = $user->phone_mob;
        $checkcode =  DB::table('checkcode')
            ->where('mobile',$mobile)
            ->where('code',$code)
            ->where('status',0)
            ->where('codetype',SMS_CODE_TYPE_RESET_PWD)
            ->first();

        if(!$checkcode){
            return $this->failure('操作已经超时，请重新验证');
        }

        $verify_time = $checkcode->expire_time;

       if($verify_time + 600 < gmtime()){
           return $this->failure('操作已经超时，请重新验证');
       }

        DB::table('member')->where('user_name',$user_name)->update(array(
            'password' =>md5($password),
        ));

        DB::table('checkcode')
            ->where('mobile',$mobile)
            ->where('code',$code)
            ->where('status',0)
            ->where('codetype',SMS_CODE_TYPE_RESET_PWD)
            ->update(['status'=>1]);

        return $this->success(null);
    }

    //修改密码
    public function modifyPwd(){
    	
        $input = Input::all();

        $rules = array(
            'password_old'  => 'required',
            'password'  => 'required|confirmed|min:6|max:16',
        );

        $validation = Validator::make($input, $rules);
        if ($validation->fails()){
            return $this->failure($validation->messages());
        }
        //用户id
        $user_id = Input::get('user_id');

        //原密码
        $password_old = Input::get('password_old');

        //新密码
        $passworld = Input::get('password');

        $user_info = DB::table('member')
            ->where('user_id',$user_id)
            ->where('password',md5($password_old))
            ->first();

        if(!$user_info)
            return $this->failure('原密码不正确。');

        DB::table('member')->where('user_id',$user_id)->update(
            array(
                'password'=>md5($passworld)
            ));

        return $this->success(null);
    }

    //修改头像
    public function updatePortrait($user_id){

        if(!$user_id){
            return $this->args_invalid();
        }

        // validate
        $input = Input::all();
        $rules = array(
            'portrait'=>'required'
        );
        $validation = Validator::make($input, $rules);

        if ($validation->fails()){
            return $this->failure($validation->messages());
        }

        $updateValues =array();
        //protrait

        //$file = Input::file('portrait');

        $filepath = '/data/portrait/' . ceil($user_id / 500) .'/' ;
        //$filename = $filepath . $user_id . '.' . $file->getClientOriginalExtension();
        $filename = $filepath . $user_id . '.jpg';

        $temps = explode(',',Input::get("portrait"));
        $img = base64_decode($temps[1]);
        //Storage::disk('local')->put($filename,$img);

        //$fp = fopen(base_path('storage/app'.$filename),"rb");
        //$buf = addslashes(fread($fp,$_FILES["portrait"]["size"]));
        //$buf = fread($fp,$_FILES["portrait"]["size"]);
        Storage::disk()->put($filename,$img);
//        unset($fp);
//        unset($buf);

//        Storage::disk('local')->delete($filename,$img);

        //unset($file);
        $updateValues['portrait']=$filename;

        /*更新*/
        if(!empty($updateValues)){
            DB::table('member')
                ->where('user_id',$user_id)
                ->update($updateValues);
        }

        $allpath = complete_url($filename.'?t='.gmtime());
        return $this->success($allpath);
    }

    private function deldir($dir){
        //先删除目录下的文件：
        $dh=opendir($dir);
        while ($file=readdir($dh)) {
            if($file!="." && $file!="..") {
                $fullpath=$dir."/".$file;
                if(!is_dir($fullpath)) {
                    unlink($fullpath);
                } else {
                    deldir($fullpath);
                }
            }
        }
        closedir($dh);
        //删除当前文件夹：
        if(rmdir($dir)) {
            return true;
        } else {
            return false;
        }
    }
    
    //获取个人信息	
    public function getProfile($user_id){       

        $user = DB::table('member')->where('user_id',$user_id)->first();

        if(!$user){
            return response()->json(array(
                'status' => RESPONSE_FAILURE,
                'code'=>'UserNotExist',
                'message' => '用户不存在',
                'auth_failure' => AUTH_FAILURE_NO,
                'data' => []
            ), 200);
            //return $this->failure('用户不存在');
        }

        // Retrieve current user info
        $info = array();

        // Data fields to return
        // birthday just below refer to baby's birthday
        $fields = array('user_id', 'user_name', 'email', 'phone_mob','wx_openid',
            'ugrade', 'portrait', 'birthday', 'nickname','wx_nickname','domicile','intro');

        // Loop through fields and set key/value of the info array
        foreach ($fields as $field) {
            if($field == 'portrait'){
                $info[$field] = complete_url($user->$field); 
            } else {
                $info[$field] = $user->$field;  
            }
        }

//        //优惠券数量
//        $couponService = new CouponService();
//        $coupon_count = $couponService->getMyCouponCount($user_id,COUPON_USEFUL);
//        $info['coupon_count'] = $coupon_count;
//
//        //收藏数量
//        $collect_count = DB::table('collect')
//            ->where('collect.user_id',$user_id)
//            ->count();
//        $info['collect_count'] = $collect_count;

        return $this->success($info);
    }

    //编辑个人信息
    public function  editProfile($user_id){
        
        // validate        
        $input = Input::all(); 
        
        $rules = array(
            'real_name'  => 'min:1|max:15',
            'email'  => 'email',   
            'phone_mob'  => 'phone', 
            'portrait'=>'image',
            'nickname'=>'',
            'domicile'=>'',
            'intro'=>''
        );
        
        $validation = Validator::make($input, $rules);
    
        if ($validation->fails()){
            return $this->failure($validation->messages());
        }
        
        if(Input::has('email')){
            if(!$this->check_email(Input::get('email'),$user_id)){
                return $this->failure('该邮箱已被注册');
            }
        }
        
        $updateValues =array();
        
        if(Input::has('real_name')){
            $updateValues['real_name']=Input::get('real_name');
        }
        if(Input::has('email')){
            $updateValues['email']=Input::get('email');
        }
        if(Input::has('phone_mob')){
            $updateValues['phone_mob']=Input::get('phone_mob');
        }
        if(Input::has('nickname')) {
            $updateValues['nickname']=Input::get('nickname');
        }
        if(Input::has('domicile')) {
            $updateValues['domicile']=Input::get('domicile');
        }
        if(Input::has('intro')) {
            $updateValues['intro']=Input::get('intro');
        }
//        //protrait
//        if(Input::hasFile('portrait')){
//
//            $file = Input::file('portrait');
//            $filepath = __DIR__.'/../../../../mall/upload/data/files/mall/portrait/' . ceil($user_id / 500);
//            $filename = uniqid('') . '.' . $file->getClientOriginalExtension();
//            Input::file('portrait')->move($filepath,$filename);
//
//            $savepath= '/data/files/mall/portrait/' . ceil($user_id / 500) . '/' . $filename;
//
//            $updateValues['portrait']=$savepath;
//
//        }
        /* 更新*/
        if(!empty($updateValues)){
            DB::table('member')
                ->where('user_id',$user_id)
                ->update($updateValues);  
        }
        
        return $this->success(null);       
    }

    /**
     *    检查电子邮件是否唯一
     *
     *    @author    maqu
     *    @param     string $email
     *    @return    bool
     */
    private function check_email($email,$user_id=0)
    {
        $query =DB::table('member')
            ->where('email',$email);
        if($user_id){
            $query->where('user_id','<>',$user_id);
        }

        $count= $query->count();
            
        return $count>0?false:true;
    }

    /**
     * 检查用户名是否唯一
     *
     * @author    maqu
     * @param     string $user_name
     * @param     string $user_name
     * @return    bool
     */
    private function check_username($user_name,$user_id=0)
    {
        $query =DB::table('member')
            ->where('user_name',$user_name);
            
        if($user_id){
            $query->where('user_id','<>',$user_id);
        }
        
        $count= $query->count();
            
        return $count>0?false:true;
    }

    private function fetchAsPortrait($url,$user_id){

        if(!$url){
            return '';
        }

        $auth = new \Qiniu\Auth(config('maqu.QINIU_ACCESS_KEY'), config('maqu.QINIU_SECRET_KEY'));
        $bmgr = new BucketManager($auth);

        $filepath = 'data/portrait/' . ceil($user_id / 500) .'/' ;
        $filename = $filepath . $user_id . '.jpg';
        $bucket = config('maqu.QINIU_BUCKET');

        list($ret, $err) = $bmgr->fetch($url, $bucket, $filename);

        Log::debug("=====> fetch $url to bucket: $bucket  key: $filename\n");

        if ($err !== null) {
            Log::debug(json_encode($err));
        } else {
            Log::debug('Success');
        }
        unset($auth,$bmgr,$filepath,$bucket);

        return $filename;

    }

    public function  wxGetSign(){

        $url = Input::get('url');
        $appid = config('maqu.WXPB_APP_ID');
        $secret = config('maqu.WXPB_APP_KEY');

        $jsapiTicket = $this->getJsApiTicket($appid,$secret);

        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId"     => $appid,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );

        return $this->success($signPackage);
    }


    private function getJsApiTicket($appid,$secret) {
        // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
        $data = json_decode(file_get_contents(__DIR__ ."/../jsapi_ticket.json"));
        if ($data->expire_time < time()) {
            $accessToken = $this->getAccessToken($appid,$secret);
            // 如果是企业号用以下 URL 获取 ticket
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->httpGet($url));
            $ticket = $res->ticket;
            if ($ticket) {
                $data->expire_time = time() + 7000;
                $data->jsapi_ticket = $ticket;
                $fp = fopen(__DIR__ ."/../jsapi_ticket.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        } else {
            $ticket = $data->jsapi_ticket;
        }

        return $ticket;
    }

    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

}
